package com.wang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.entity.TbBbsArticle;
import com.wang.response.ResultResponse;
import com.wang.service.TbBbsArticleService;
import com.wang.mapper.TbBbsArticleMapper;
import com.wang.unitl.SensitiveWordInit;
import com.wang.unitl.SensitivewordFilter;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
/**
 *  文章
 */
@Service
public class TbBbsArticleServiceImpl implements TbBbsArticleService{
    @Resource
    private TbBbsArticleMapper tbBbsArticleMapper;
    @Resource
    private TbBbsArticleServiceImpl tbBbsArticleService;

    /**
     *  查询所有
     * @param tbBbsArticle
     * @return
     */
    @Override
    public ResultResponse findBbsArticle(TbBbsArticle tbBbsArticle) {
        Page<TbBbsArticle> page = new Page<>(tbBbsArticle.getPagenum(), tbBbsArticle.getPagesize());
        QueryWrapper<TbBbsArticle> querywrapper=new QueryWrapper<>();
        querywrapper.eq("audit_flag", 1);
        Page<TbBbsArticle> selectPage = tbBbsArticleMapper.selectPage(page, querywrapper);
        long total = selectPage.getTotal();
        return ResultResponse.SUCCESS(selectPage.getRecords(),total);
    }

    /**
     * 查询用户发布的
     * @param userId
     * @return
     */
    @Override
    public ResultResponse findBbsArticleuid(Integer userId) {
        QueryWrapper<TbBbsArticle> querywrapper=new QueryWrapper<>();
        querywrapper.eq("audit_flag", 1);
        querywrapper.eq("user_id", userId);
        List<TbBbsArticle> tbBbsArticles = tbBbsArticleMapper.selectList(querywrapper);
        return ResultResponse.SUCCESS(tbBbsArticles);
    }


    //敏感词拦截
    @Override
    public ResultResponse insertBbsArticle(TbBbsArticle tbBbsArticle) throws Exception {
        List<String> datas = SensitiveWordInit.readSensitiveWordFile();
        //初始化词库,读取敏感词库，将敏感词放入HashSet中，构建一个DFA算法模型：
        SensitiveWordInit.init(datas);
        //输入的字符串
        //List<String> rep = SensitivewordFilter.getSensitiveWord(datas,str,1);
        String rep = SensitivewordFilter.replaceSensitiveWord(datas, tbBbsArticle.getFileContents(), 1, "*");
        tbBbsArticle.setFileContents(rep);
        if (tbBbsArticle.getFileId() != null) {
            int i = tbBbsArticleMapper.updateById(tbBbsArticle);
            if (i > 0) {
                return ResultResponse.SUCCESS();
            } else {
                return ResultResponse.FAIED(-1, "修改失败");
            }
        } else {
            //判断是否用敏感词
            if (rep!=null){
                 tbBbsArticle.setAuditFlag(0);
            }
            int insert = tbBbsArticleMapper.insert(tbBbsArticle);
            if (insert > 0) {
                return ResultResponse.SUCCESS();
            } else {
                return ResultResponse.FAIED(-1, "添加失败");
            }
        }
    }

    @Override
    public ResultResponse removeBbsArticle(Integer fileId) {
        int i = tbBbsArticleMapper.deleteById(fileId);
        if (i>0){
            return ResultResponse.SUCCESS();
        }else{
            return ResultResponse.FAIED(-1,"删除失败");
        }
    }

    @Override
    public ResultResponse findaudit(Integer pagenum, Integer pagesize) {
        Page<TbBbsArticle> page = new Page<>(pagenum, pagesize);
        QueryWrapper<TbBbsArticle> wrapper = new QueryWrapper<>();
        wrapper.ne("audit_flag", 1);
        Page<TbBbsArticle> page1 = tbBbsArticleMapper.selectPage(page, wrapper);

        long total = page1.getTotal();
        return ResultResponse.SUCCESS(page1.getRecords(),total);
    }

    @Override
    public ResultResponse updateaudit(TbBbsArticle tbBbsArticle) {
        int i = this.tbBbsArticleMapper.updateById(tbBbsArticle);
        if (i>0){
             return ResultResponse.SUCCESS();
        }else {
           return ResultResponse.FAIED(-1, "失败");
        }
    }

     @Autowired
    private RestHighLevelClient restHighLevelClient;

   //增量同步
    @Scheduled(cron = "0 0/10 * * * *")
    public void increment() throws IOException {
        List<TbBbsArticle> list = tbBbsArticleMapper.selectList(null);
        BulkRequest bulkRequest = new BulkRequest("TbBbsArticle");
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(
                    new IndexRequest().id(list.get(i).getFileId() + "").source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        }
    }


    @Override
    public ResultResponse findes(TbBbsArticle tbBbsArticle) throws IOException {
        HashMap map = new HashMap();
        ArrayList list = new ArrayList();
        SearchRequest request = new SearchRequest("TbBbsArticle");
        SearchSourceBuilder builder = new SearchSourceBuilder();


        builder.from((tbBbsArticle.getPagenum()-1)*tbBbsArticle.getPagesize());
        builder.size(tbBbsArticle.getPagesize());
        request.source(builder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = search.getHits().getHits();
        long total = search.getHits().getTotalHits().value;
        for (SearchHit hit : hits) {
            String asString = hit.getSourceAsString();
            TbBbsArticle user1 = JSON.parseObject(asString, TbBbsArticle.class);
            list.add(user1);
        }
        map.put("total", total);
        map.put("list", list);
        return ResultResponse.SUCCESS(map);
    }

    @Override
    public ResultResponse findall() {
        List<TbBbsArticle> tbBbsArticles = this.tbBbsArticleMapper.selectList(null);
        return ResultResponse.SUCCESS(tbBbsArticles);
    }


}



